package cn.t.facade.user;


import cn.t.converter.user.CustomerFirmDTOConverter;
import cn.t.core.exception.BizException;
import cn.t.core.facade.FacadeImpl;
import cn.t.dto.user.CustomerFirmDTO;
import cn.t.core.enums.base.CommonError;
import cn.t.model.user.CostCenterDO;
import cn.t.model.user.CustomerFirmDO;
import cn.t.model.user.UserQueryDO;
import cn.t.service.user.CostCenterService;
import cn.t.service.user.CustomerFirmService;
import cn.t.service.user.UserQueryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 单位信息表服务编排
 *
 * @author l
 */
@Slf4j
@Service
@AllArgsConstructor
public class CustomerFirmFacade extends FacadeImpl<CustomerFirmDTO, CustomerFirmDO, CustomerFirmDTOConverter, CustomerFirmService> {


    @Override
    public boolean update(CustomerFirmDTO dto) {
        service.isDuplicatedFirm(dto.getId(), dto.getFirmCode());
        boolean result = service.update(converter.dto2Model(dto));
        userQueryFacade.updateByFirmId(dto.getId());
        return result;
    }

    @Override
    public boolean remove(Long firmId) {

        List<UserQueryDO> userQueryList = userQueryService.findByFirmIdIgnoreDisable(firmId);
        if (!CollectionUtils.isEmpty(userQueryList)) {
            String errorMessage = String.format("指定的公司已绑定用户，不可删除。firmId=%s ", firmId);
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
        }

        List<Long> firmIds = new ArrayList<>();
        firmIds.add(firmId);
        List<CostCenterDO> costCenterList = costCenterService.findByFirm(firmIds);
        if (!CollectionUtils.isEmpty(costCenterList)) {
            String errorMessage = String.format("指定的公司已绑定成本中心，不可删除。firmId=%s ", firmId);
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
        }


        boolean result = service.removeById(firmId);
        userQueryFacade.updateByFirmId(firmId);
        return result;
    }

    public CustomerFirmDTO queryFirmByCode(String firmCode) {
        return this.converter.model2Dto(this.service.queryFirmByCode(firmCode));
    }

    @Autowired
    private UserQueryFacade userQueryFacade;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private CostCenterService costCenterService;
}

